package com.husong.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.husong.cons.MessageCons;
import com.husong.cons.OrderCons;
import com.husong.cons.OrderConstants;
import com.husong.cons.ProgressCons;
import com.husong.cons.TagConstants;
import com.husong.entity.BatchWithdrawOrder;
import com.husong.entity.Feedback;
import com.husong.entity.Institution;
import com.husong.entity.Invite;
import com.husong.entity.Message;
import com.husong.entity.OrderProgress;
import com.husong.entity.PayOrder;
import com.husong.entity.RechargeList;
import com.husong.entity.Red;
import com.husong.entity.TrainPic;
import com.husong.entity.TrainTest;
import com.husong.entity.User;
import com.husong.entity.WithdrawOrder;
import com.husong.impl.base.BaseService;
import com.husong.pojo.AccountBindBean;
import com.husong.pojo.ActivityFundPoolBean;
import com.husong.pojo.ActivityFundPoolLogBean;
import com.husong.pojo.BillBean;
import com.husong.pojo.OrderBean;
import com.husong.pojo.PayOrderBean;
import com.husong.pojo.UserModel;
import com.husong.pojo.UserWalletBean;
import com.husong.pojo.UserWalletLogBean;
import com.husong.pojo.WalletBean;
import com.husong.pojo.WithdrawOrderBean;
import com.husong.pojo.WxPayResult;
import com.husong.service.UserDataService;
import com.husong.util.JPush;
import com.husong.util.MD5Util;
import com.husong.util.PayOrderNoUtil;
import com.husong.util.UUIDUtil;
import com.husong.util.alipay.util.AlipayNotify;

import cn.jpush.api.JPushClient;

/**
 * @author MaxMin.
 */
public class UserServiceImpl extends BaseService implements UserDataService {

    /**
     * 查询所有经纪人数量
     *
     * @return
     */
    @Override
    public Long brokerCount(String cityname) {
        return userMapper.brokerCount(cityname);
    }

    @Override
    public User regist(String telephone, String cityname, String code) {
        User user = new User();
        String uid=UUIDUtil.getUUID();
        user.setUserId(uid);
        user.setTelephone(telephone);
        user.setCityName(cityname);
        user.setHeader("http://static.image.alimmdn.com/image_2fc5835ce44e44d6b27097a9db7d36a7?t=1443422565001");
        user.setNotifyid(MD5Util.MD5(UUIDUtil.getUUID()));
        user.setCreateDate(new Timestamp(System.currentTimeMillis()));
        user.setUsername("呼送雇主");
        user.setBirthday(new Timestamp(System.currentTimeMillis()));
        int rt = userMapper.addUser(user);
        final String userid=uid;
        final String city=cityname;
        final String tele=code;
        new Thread(new Runnable() {
			@Override
			public void run() {
				Calendar today=Calendar.getInstance();
				today.add(Calendar.DAY_OF_MONTH, 30);
				Red red=new Red();
				red.setActive_begin_time(new Timestamp(System.currentTimeMillis()));
				red.setActive_end_time(new Timestamp(today.getTime().getTime()));
				red.setAmount(BigDecimal.valueOf(10));
				red.setCityname(city);
				red.setCreate_date(new Timestamp(System.currentTimeMillis()));
				red.setId(UUIDUtil.getUUID());
				red.setRed_desc("新手红包10元");
				red.setRed_status(1);
				red.setRed_type(1);
				red.setUser_id(userid);
				orderMapper.addRed(red);
				//推荐有奖
				if(tele!=null&&!"".equals(tele)){
					User u=userMapper.getUserByTelephone(tele);
					if(u!=null){
						Invite invite=new Invite();
						invite.setCreate_time(new Timestamp(System.currentTimeMillis()));
						invite.setInvite_user_id(u.getUserId());
						invite.setUser_id(userid);
						invite.setStatus(1);
						userMapper.addInvite(invite);
						
						Map<String, Object> params=new HashMap<String, Object>();
						params.put("point", 5);
						params.put("user_id", userid);
						userMapper.updatePoint(params);
					}
				}
				
				Message message = new Message("成功注册，系统为您送出一个红包，赶快使用吧！", userid, MessageCons.USER_TYPE_USER, MessageCons.MESSAGE_TYPE_ORDER);
				message.setCreatetime(new Timestamp(System.currentTimeMillis()));
				orderMapper.addMessage(message);
			}
		}).start();
        if (rt > 0) {
            return user;
        }
        return null;
    }

    @Override
    public User login(String telephone) {
        return userMapper.getUserByTelephone(telephone);
    }

    @Override
    public boolean checkUserIsExsit(String telephone) {
        User user = userMapper.getUserByTelephone(telephone);
        return user!=null;
    }

    /**
     * 根据id获取用户
     *
     * @param id
     *
     * @return
     */
    @Override
    public User get(String id) {
        return userMapper.getUserById(id);
    }

	@Override
	public List<TrainPic> trainPics() {
		return userMapper.trainPics();
	}

	@Override
	public List<TrainTest> trainTests() {
		return userMapper.trainTests();
	}

	@Override
	public int trained(String brokerid) {
		return userMapper.trained(brokerid);
	}

	@Override
	public int tested(String brokerid) {
		return userMapper.tested(brokerid);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public int authen(User user) {
		user.setCreateDate(new Timestamp(System.currentTimeMillis()));
		user.setTag(TagConstants.BROKER);
		int count=userMapper.submit_authen(user);
		count=userMapper.save_broker_info(user);
		return count;
	}

	@Override
	public UserWalletBean getUserWalletBeanByUserId(String userId) {
		return userMapper.getUserWalletBeanByUserId(userId);
	}

	@Override
	public UserWalletBean getUsefullUserWalletBeanByUserId(String userId) {
		return userMapper.getUsefullUserWalletBeanByUserId(userId);
	}

	@Override
	public int addUserWallet(String user_id) {
		UserWalletBean wallet=userMapper.getUsefullUserWalletBeanByUserId(user_id);
		if(wallet!=null){
			return 1;
		}else{
			wallet=new UserWalletBean();
		}
		wallet.setCreate_time(new Timestamp(System.currentTimeMillis()));
		wallet.setFrozen_amount(BigDecimal.ZERO);
		wallet.setPay_password(null);
		wallet.setPurchase_amount(BigDecimal.ZERO);
		wallet.setRecharge_amount(BigDecimal.ZERO);
		wallet.setStatus(1);
		wallet.setTip_amount(BigDecimal.ZERO);
		wallet.setUser_id(user_id);
		return userMapper.addUserWallet(wallet);
	}

	@Override
	public int updateWalletPassword(String user_id, String password) {
		UserWalletBean wallet=userMapper.getUsefullUserWalletBeanByUserId(user_id);
		if(wallet==null){
			wallet=new UserWalletBean();
			wallet.setCreate_time(new Timestamp(System.currentTimeMillis()));
			wallet.setFrozen_amount(BigDecimal.ZERO);
			wallet.setPay_password(null);
			wallet.setPurchase_amount(BigDecimal.ZERO);
			wallet.setRecharge_amount(BigDecimal.ZERO);
			wallet.setStatus(1);
			wallet.setTip_amount(BigDecimal.ZERO);
			wallet.setUser_id(user_id);
			userMapper.addUserWallet(wallet);
		}
		wallet.setPay_password(password);
		wallet.setUser_id(user_id);
		return userMapper.updateWalletPassword(wallet);
	}

	@Override
	public int addAccountBind(AccountBindBean bean) {
		return userMapper.addAccountBind(bean);
	}

	@Override
	public int updateAccountBind(AccountBindBean bean) {
		return userMapper.updateAccountBind(bean);
	}

	@Override
	public AccountBindBean getAccountBind(String id) {
		return userMapper.getAccountBind(id);
	}

	@Override
	public List<AccountBindBean> getAccountBinds(String user_id) {
		return userMapper.getAccountBinds(user_id);
	}

	@Override
	public int updateUser(UserModel user) {
		return userMapper.updateUser(user);
	}

	@Override
	public int declare(String user_id, String declaration) {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("declaration", declaration);
		params.put("user_id", user_id);
		return userMapper.declare(params);
	}

	@Override
	public PayOrder addPayOrder(String user_id, String order_id, Integer coupon_type, String coupon_id, Integer pay_type,
			Integer pay_way) {
		BigDecimal amount=BigDecimal.ZERO;
		if(pay_way==2){//直接支付
			OrderBean order=orderMapper.get(order_id);
			amount=order.getFee().add(order.getTip()).subtract(order.getDiscount());
			if(coupon_type==1){//优惠券
				Red red=orderMapper.getRed(coupon_id);
				amount=amount.subtract(red.getAmount());
				
			}
			
			if(pay_type==2||pay_type==4){
				UserWalletBean wallet=userMapper.getUserWalletBeanByUserId(user_id);
				if(wallet!=null){
					BigDecimal balance=wallet.getRecharge_amount();
					if(balance.doubleValue()>0&&balance.doubleValue()<amount.doubleValue()){
						amount.subtract(balance);
					}
				}
			}
			
			if(amount.doubleValue()<=0){
				amount=BigDecimal.valueOf(0.01);
			}
			
		}else if(pay_way==1){//充值
			RechargeList recharge=userMapper.getRechargeList(order_id);
			amount=recharge.getAmount();
		}
		PayOrderBean pay=new PayOrderBean();
		String id=UUIDUtil.getUUID();
		String pay_order_no=PayOrderNoUtil.getPayOrderNo();
		pay.setAmount(amount);
		pay.setCoupon_id(coupon_id);
		pay.setCoupon_type(coupon_type);
		pay.setCreate_time(new Timestamp(System.currentTimeMillis()));
		pay.setId(id);
		pay.setOrder_id(order_id);
		pay.setPay_order_no(pay_order_no);
		pay.setPay_type(pay_type);
		pay.setPay_way(pay_way);
		pay.setStatus(0);
		pay.setUser_id(user_id);
		userMapper.addPayOrder(pay);
		PayOrder payOrder=getPayOrderById(id);
		return payOrder;
	}

	@Override
	public PayOrder getPayOrderById(String id) {
		return userMapper.getPayOrderById(id);
	}

	@Override
	public PayOrder getPayOrderByPayOrderNo(String pay_order_no) {
		return userMapper.getPayOrderByPayOrderNo(pay_order_no);
	}

	@Override
	public List<RechargeList> getRechargeLists() {
		return userMapper.getRechargeLists();
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public int addWithdrawOrder(WithdrawOrderBean withdraw) {
		UserWalletBean wallet=userMapper.getUsefullUserWalletBeanByUserId(withdraw.getUser_id());
		double num = withdraw.getWithdraw_amount().doubleValue();
		double purchaseBalance = wallet.getPurchase_amount().doubleValue();
		double dPurchase = 0;
		double dTip = 0;
		if (num <= purchaseBalance) {
			dPurchase = num;
		} else {
			dPurchase = purchaseBalance;
			dTip = num - purchaseBalance;
		}
		double tipBalance=dTip;
		BigDecimal service_amount=BigDecimal.ZERO;
		if (tipBalance <= 0) {
			tipBalance= 0;
			withdraw.setService_amount(BigDecimal.ZERO);
		} else if (tipBalance>0&&tipBalance < 50) {
			tipBalance= tipBalance+5;
			service_amount=BigDecimal.valueOf(5D*-1);
			withdraw.setService_amount(service_amount);
		} else {
			tipBalance = tipBalance / 0.9;
			service_amount=BigDecimal.valueOf(tipBalance*0.1*-1);
			withdraw.setService_amount(service_amount);
		}
		UserWalletLogBean brokerWalletLog=new UserWalletLogBean();
		brokerWalletLog.setPurchase_amount(BigDecimal.valueOf(Math.abs(dPurchase)*-1));
		brokerWalletLog.setTip_amount(BigDecimal.valueOf(Math.abs(tipBalance)*-1));
		brokerWalletLog.setId(UUIDUtil.getUUID());
		brokerWalletLog.setOrder_id(withdraw.getId());
		brokerWalletLog.setTrade_desc("提现");
		brokerWalletLog.setTrade_type(4);
		brokerWalletLog.setTrade_time(new Timestamp(System.currentTimeMillis()));
		brokerWalletLog.setUser_id(withdraw.getUser_id());
		brokerWalletLog.setOrder_no(withdraw.getWithdraw_order_no());
		brokerWalletLog.setService_amount(service_amount);;
		userMapper.addWalletLog(brokerWalletLog);
		Map<String,Object> brokerParams=new HashMap<String, Object>();
		brokerParams.put("user_id",withdraw.getUser_id());
		brokerParams.put("purchase_amount", BigDecimal.valueOf(Math.abs(dPurchase)));
		brokerParams.put("tip_amount", BigDecimal.valueOf(Math.abs(tipBalance)));
		userMapper.frozenBrokerBalance(brokerParams);
		return userMapper.addWithdrawOrder(withdraw);
	}

	@Override
	public List<WalletBean> getBills(String user_id, String lastDateStr, Long lastrowid) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		List<WalletBean> bills=userMapper.getBills(params);
		return bills;
	}
	@Override
	public List<BillBean> getBillsByType(String user_id, String lastDateStr, Long lastrowid,int type) {
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("lastrowid", lastrowid);
		params.put("lastDate", lastDateStr);
		params.put("type", type);
		List<BillBean> bills=userMapper.getBillsByType(params);
		return bills;
	}

	@Override
	public int addFeedback(Feedback feedback) {
		return userMapper.addFeedback(feedback);
	}

	@Override
	public BigDecimal getPurchaseSumAmount(String user_id) {
		// TODO Auto-generated method stub
		return userMapper.getPurchaseSumAmount(user_id);
	}

	@Override
	public BigDecimal getTipSumAmount(String user_id) {
		// TODO Auto-generated method stub
		return userMapper.getTipSumAmount(user_id);
	}

	@Override
	public BigDecimal getWithdrawSumAmount(String user_id) {
		// TODO Auto-generated method stub
		return userMapper.getWithdrawSumAmount(user_id);
	}

	@Override
	public void notifyWeixinUser(WxPayResult wpr) {
		Double fee=Double.parseDouble(wpr.getTotalFee())/100;
		String total_fee=fee+"";
		String out_trade_no=wpr.getOutTradeNo();
		PayOrder pay=userMapper.getPayOrderByPayOrderNo(out_trade_no);
		if(pay.getPay_way()==1){//充值
			doneRechargePayment(pay, total_fee, out_trade_no);
		}else{//直接支付
			doneOrderPayment(pay, total_fee, out_trade_no);
		}
	}

	@Override
	public String notifyAlipayUser(ServletRequest sr) throws Exception {
		HttpServletRequest request = (HttpServletRequest) sr;
		// 获取支付宝POST过来反馈信息
				Map<String, String> params = new HashMap<String, String>();
				Map requestParams = request.getParameterMap();
				for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
					String name = (String) iter.next();
					String[] values = (String[]) requestParams.get(name);
					String valueStr = "";
					for (int i = 0; i < values.length; i++) {
						valueStr = (i == values.length - 1) ? valueStr + values[i]
								: valueStr + values[i] + ",";
					}
					// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
					// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
					// "gbk");
					params.put(name, valueStr);
				}
				// 商户订单号
				String out_trade_no = new String(request.getParameter("out_trade_no")
						.getBytes("ISO-8859-1"), "UTF-8");
				// 商户金额
				String total_fee = new String(request.getParameter("total_fee")
						.getBytes("ISO-8859-1"), "UTF-8");
				// 支付宝交易号
//				String trade_no = new String(request.getParameter("trade_no").getBytes(
//						"ISO-8859-1"), "UTF-8");
				// 交易状态
				String trade_status = new String(request.getParameter("trade_status")
						.getBytes("ISO-8859-1"), "UTF-8");
				if (AlipayNotify.verifyRSA(params)) {// 验证成功
					if (trade_status.equals("TRADE_FINISHED")
							|| trade_status.equals("TRADE_SUCCESS")) {
						PayOrder pay=userMapper.getPayOrderByPayOrderNo(out_trade_no);
						if(pay.getPay_way()==1){//充值
							doneRechargePayment(pay, total_fee, out_trade_no);
						}else{//直接支付
							doneOrderPayment(pay, total_fee, out_trade_no);
						}
					}
					return "success";
				} else {// 验证失败
					return "fail";
				}
	}
	
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void doneRechargePayment(PayOrder pay,String total_fee,String out_trade_no){
		// 获取用户id及充值金额
				String userid = pay.getUser_id();
				int hsOrderStatus = pay.getStatus();
				String orderId = pay.getOrder_id();
				// double amount = (Double) hsOrderInfo.get("amount");
				if (hsOrderStatus == 0) {
//					Map<String,Object> rechargeMap=walletMapper.queryRechargeAmount(orderId);
					RechargeList recharge=userMapper.getRechargeList(orderId);
					BigDecimal rechargeAmount=recharge.getAmount();
					BigDecimal giveAmount=recharge.getGive_amount();
					int count=userMapper.queryRechargeWalletLogCount(userid);
					if(count>0){//首次充值才送钱
						giveAmount=BigDecimal.valueOf(0);
					}
					double amount = Double.parseDouble(total_fee);
					
					// 1,修改支付订单状态为支付成功
					userMapper.payed(out_trade_no);
					if(amount<rechargeAmount.doubleValue()){
						
					}else{
						BigDecimal addAmount=rechargeAmount.add(giveAmount);
						amount=addAmount.doubleValue();
					}
					//1.扣除用户余额
					Map<String,Object> userParams=new HashMap<String, Object>();
					userParams.put("user_id", userid);
					userParams.put("recharge_amount", rechargeAmount.add(giveAmount));
					userMapper.updateBalance(userParams);
					//2.增加用户钱包记录
					UserWalletLogBean userWalletLog=new UserWalletLogBean();
					userWalletLog.setAmount(rechargeAmount.add(giveAmount));
					userWalletLog.setId(UUIDUtil.getUUID());
					userWalletLog.setOrder_id(orderId);
					userWalletLog.setTrade_type(1);
					userWalletLog.setTrade_desc("充值");
					userWalletLog.setTrade_time(new Timestamp(System.currentTimeMillis()));
					userWalletLog.setUser_id(userid);
					userWalletLog.setOrder_no(out_trade_no);
					userMapper.addWalletLog(userWalletLog);
					
					if(giveAmount.doubleValue()>0){
						Map<String,Object> redparams=new HashMap<String,Object>();
						redparams.put("activity_type", 3);
						redparams.put("city_name", recharge.getCity_name());
						ActivityFundPoolBean redpool=orderMapper.getActivityFundPool(redparams);
						
						Map<String,Object> redupdate=new HashMap<String,Object>();
						redupdate.put("id", redpool.getId());
						redupdate.put("amount", giveAmount);
						orderMapper.updateActivityFundPool(redupdate);
						//8.资金池记录
						ActivityFundPoolLogBean redlog=new ActivityFundPoolLogBean();
						redlog.setId(UUIDUtil.getUUID());
						redlog.setActivity_desc("首次充值赠送金额");
						redlog.setActivity_type(3);
						redlog.setAmount(giveAmount);
						redlog.setCity_name(recharge.getCity_name());
						redlog.setCreate_time(new Timestamp(System.currentTimeMillis()));
						redlog.setFund_code(redpool.getFund_code());
						redlog.setFund_id(redpool.getId());
						redlog.setOrder_id(orderId);
						redlog.setUser_id(userid);
						orderMapper.addActivityFundPoolLog(redlog);
					}
				}
	}
	
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void doneOrderPayment(PayOrder pay,String total_fee,String out_trade_no){
		int hsOrderStatus = (Integer) pay.getStatus();
		String thisOrderId = pay.getOrder_id();
		String redid = pay.getCoupon_id();
		if (hsOrderStatus == 0) {
			// 1,修改支付订单状态为支付成功
//			walletMapper.updateUserOrderStatus(out_trade_no);
			userMapper.payed(out_trade_no);
			// 2,查询呼单信息，获取该单的消费和代购额
//			Map<String, Object>  temp1 = orderMapper.getOrderFeeInfo(hsOrderId);
			OrderBean order =orderMapper.get(thisOrderId);
			Integer status=order.getOrder_status_id();
			final String userid=order.getUser_id();
			if(status>7){//如果状态为8表示已支付
//				logger.info("done_order,out param，该呼单已被支付，status："+status);
				return;
			}
			Double totalFee=Double.parseDouble(total_fee);
			double tip = (Double) order.getTip().doubleValue();
			double fee = (Double) order.getFee().doubleValue();
			double discount = (Double) order.getDiscount().doubleValue();
			double orderTotalFee=tip+fee-discount;
			BigDecimal giveMoney =new BigDecimal(0);
			
			Red red=null;
			if(redid!=null&&!"".equals(redid.trim())){
				red=orderMapper.getRed(redid);
				giveMoney=red.getAmount();
			}
			orderTotalFee=orderTotalFee-giveMoney.doubleValue();
			if(pay.getPay_type()==2||pay.getPay_type()==4){
				double balance=orderTotalFee-totalFee;
				//1.扣除用户余额
				Map<String,Object> userParams=new HashMap<String, Object>();
				userParams.put("user_id", pay.getUser_id());
				userParams.put("recharge_amount", BigDecimal.valueOf(balance*-1));
				userMapper.updateBalance(userParams);
				//2.增加用户钱包记录
				UserWalletLogBean userWalletLog=new UserWalletLogBean();
				userWalletLog.setAmount(BigDecimal.valueOf(balance*-1));
				userWalletLog.setId(UUIDUtil.getUUID());
				userWalletLog.setOrder_id(order.getId());
				userWalletLog.setTrade_type(3);
				if(order.getOrder_type_id()==1){
					
					userWalletLog.setTrade_desc("代办");
				}else if(order.getOrder_type_id()==2){
					
					userWalletLog.setTrade_desc("代购");
				}else if(order.getOrder_type_id()==3){
					
					userWalletLog.setTrade_desc("代送");
				}
				userWalletLog.setTrade_time(new Timestamp(System.currentTimeMillis()));
				userWalletLog.setUser_id(pay.getUser_id());
				userWalletLog.setOrder_no(order.getOrder_no());
				userMapper.addWalletLog(userWalletLog);
			}else{
				if(orderTotalFee>totalFee){
//				logger.info("done_order,out param，呼单总额与实际支付金额不一致，orderTotalFee："+orderTotalFee+",totalFee:"+totalFee);
					return;
				}
			}
			
			//3.给经纪人钱包加钱
			Map<String,Object> brokerParams=new HashMap<String, Object>();
			UserWalletBean brokerWallet=userMapper.getUsefullUserWalletBeanByUserId(order.getBroker_id());//判断经纪人钱包是否存在
			if(brokerWallet==null){
				brokerWallet=new UserWalletBean();
				brokerWallet.setCreate_time(new Timestamp(System.currentTimeMillis()));
				brokerWallet.setFrozen_amount(BigDecimal.ZERO);
				brokerWallet.setPay_password(null);
				brokerWallet.setPurchase_amount(BigDecimal.ZERO);
				brokerWallet.setRecharge_amount(BigDecimal.ZERO);
				brokerWallet.setStatus(1);
				brokerWallet.setTip_amount(BigDecimal.ZERO);
				brokerWallet.setUser_id(order.getBroker_id());
				userMapper.addUserWallet(brokerWallet);
			}
			brokerParams.put("user_id", order.getBroker_id());
			brokerParams.put("purchase_amount", fee);
			brokerParams.put("tip_amount", tip);
			userMapper.updateBrokerBalance(brokerParams);
			//4.增加经纪人钱包记录
			UserWalletLogBean brokerWalletLog=new UserWalletLogBean();
			brokerWalletLog.setPurchase_amount(order.getFee());
			brokerWalletLog.setTip_amount(order.getTip());
			brokerWalletLog.setId(UUIDUtil.getUUID());
			brokerWalletLog.setOrder_id(order.getId());
			if(order.getOrder_type_id()==1){
				
				brokerWalletLog.setTrade_desc("代办");
			}else if(order.getOrder_type_id()==2){
				
				brokerWalletLog.setTrade_desc("代购");
			}else if(order.getOrder_type_id()==3){
				
				brokerWalletLog.setTrade_desc("代送");
			}
			brokerWalletLog.setTrade_type(2);
			brokerWalletLog.setTrade_time(new Timestamp(System.currentTimeMillis()));
			brokerWalletLog.setUser_id(order.getBroker_id());
			brokerWalletLog.setOrder_no(order.getOrder_no());
			userMapper.addWalletLog(brokerWalletLog);
			//5.修改订单状态
			Map<String,Object> orderParams=new HashMap<String,Object>();
			orderParams.put("status", 8);
			orderParams.put("orderid", order.getId());
			orderParams.put("oriStatus", order.getOrder_status_id());
			orderMapper.updateOrderStatus(orderParams);
			//6.红包状态修改
			if(redid!=null&&!"".equals(redid.trim())){
				Map<String,Object> redParams=new HashMap<String,Object>();
				redParams.put("red_status", 2);
				redParams.put("order_id", order.getId());
				redParams.put("id", redid);
				orderMapper.updateRed(redParams);
				//7.资金池修改
				if(fee+tip-discount<giveMoney.doubleValue()){
					giveMoney=BigDecimal.valueOf(fee+tip-discount);
				}
				
				Map<String,Object> redparams=new HashMap<String,Object>();
				redparams.put("activity_type", 2);
				redparams.put("city_name", order.getCityname());
				ActivityFundPoolBean redpool=orderMapper.getActivityFundPool(redparams);
				
				Map<String,Object> redupdate=new HashMap<String,Object>();
				redupdate.put("id", redpool.getId());
				redupdate.put("amount", giveMoney);
				orderMapper.updateActivityFundPool(redupdate);
				//8.资金池记录
				ActivityFundPoolLogBean redlog=new ActivityFundPoolLogBean();
				redlog.setId(UUIDUtil.getUUID());
				redlog.setActivity_desc("新手红包优惠");
				redlog.setActivity_type(2);
				redlog.setAmount(giveMoney);
				redlog.setCity_name(order.getCityname());
				redlog.setCreate_time(new Timestamp(System.currentTimeMillis()));
				redlog.setFund_code(redpool.getFund_code());
				redlog.setFund_id(redpool.getId());
				redlog.setOrder_id(order.getId());
				redlog.setUser_id(order.getUser_id());
				orderMapper.addActivityFundPoolLog(redlog);
			}
			
			if(discount>0){
				//7.资金池修改
				Map<String,Object> discountparams=new HashMap<String,Object>();
				discountparams.put("activity_type", 1);
				discountparams.put("city_name", order.getCityname());
				ActivityFundPoolBean discountpool=orderMapper.getActivityFundPool(discountparams);
				
				Map<String,Object> discountupdate=new HashMap<String,Object>();
				discountupdate.put("id", discountpool.getId());
				discountupdate.put("amount", discount);
				orderMapper.updateActivityFundPool(discountupdate);
				//8.资金池记录
				ActivityFundPoolLogBean discountlog=new ActivityFundPoolLogBean();
				discountlog.setId(UUIDUtil.getUUID());
				discountlog.setActivity_desc("商品折扣");
				discountlog.setActivity_type(1);
				discountlog.setAmount(BigDecimal.valueOf(discount));
				discountlog.setCity_name(order.getCityname());
				discountlog.setCreate_time(new Timestamp(System.currentTimeMillis()));
				discountlog.setFund_code(discountpool.getFund_code());
				discountlog.setFund_id(discountpool.getId());
				discountlog.setOrder_id(order.getId());
				discountlog.setUser_id(order.getUser_id());
				orderMapper.addActivityFundPoolLog(discountlog);
			}
			
			final String orderId=order.getId();
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					//极光推送
					OrderBean order=orderMapper.get(orderId);
					Message message = new Message(OrderCons.PAY_SUCCESS, order.getBroker_id(),
							MessageCons.USER_TYPE_BROKER,
							MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderMapper.addMessage(message);
					//呼单状态记录
						OrderProgress progress=new OrderProgress();
						progress.setId(UUIDUtil.getUUID());
						progress.setUser_msg(ProgressCons.ORDER_PAYED_MSG);
						progress.setContent(ProgressCons.ORDER_PAYED_CONTENT);
						progress.setOrderid(orderId);
						progress.setOrder_status(OrderConstants.ORDER_NEED_EVALUATE);
						progress.setCreate_date(new Timestamp(System.currentTimeMillis()));
						orderMapper.addOrderProgress(progress);
					
				}
			}).start();
			
		}
	}

	@Override
	public int addRed(Red red) {
		return orderMapper.addRed(red);
	}

	@Override
	public BigDecimal getInviteAmount(String user_id) {
		return orderMapper.getInviteAmount(user_id);
	}

	@Override
	public int updateUserTag(String user_id, String tag) {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("user_id", user_id);
		params.put("tag", tag);
		return userMapper.updateUserTag(params);
	}

	@Override
	public List<Institution> getInstitutions() {
		return userMapper.getInstitutions();
	}
	@Override
	public List<WithdrawOrder> queryAliWithdrawOrdersByBatchOrderNo(
			String batchOrderNo) {
		return userMapper.queryAliWithdrawOrderByBatchOrderNo(batchOrderNo);
	}
	
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void dealWithSuccessAliBatchWithdrawResult(
			Map<String, WithdrawOrder> successMap, String batch_no,String notify_id) {
		BatchWithdrawOrder batchOrder=userMapper.queryBatchWithdrawOrderByOrderNo(batch_no);
		Map<String,BigDecimal> moneyMap=new HashMap<String, BigDecimal>();
		Map<String,String> reasonMap=new HashMap<String, String>();
		List<String> orderIds=new ArrayList<String>();
		List<String> ids=new ArrayList<String>();
		final List<String> brokerids=new ArrayList<String>();
		 
		for (Entry<String, WithdrawOrder> entry : successMap.entrySet()) {
			WithdrawOrder order=entry.getValue();
			if(order!=null){
				ids.add(order.getUser_id());
				brokerids.add(order.getUser_id());
				orderIds.add(order.getWithdrawid());
				if(moneyMap.containsKey(order.getUser_id())){
					moneyMap.put(order.getUser_id(), moneyMap.get(order.getUser_id()).add(order.getWithdraw_amount()).add(order.getService_amount()));
				}else{
					moneyMap.put(order.getUser_id(), order.getWithdraw_amount().add(order.getService_amount()));
				}
				reasonMap.put(order.getWithdrawid(), order.getNotify_desc());
			}
		}
		Map<String,Object> param=new HashMap<String, Object>();
		param.put("moneyMap", moneyMap);
		param.put("ids", ids);
		userMapper.batchDeductBrokerWallet(param);//扣除冻结的钱
		
		Map<String,Object> orderParam=new HashMap<String, Object>();
		orderParam.put("status", 2);//表示提现成功
		orderParam.put("finishTime", Calendar.getInstance());
		orderParam.put("batchOrderId", batchOrder.getId());
		orderParam.put("ids", orderIds);
		orderParam.put("reasonMap", reasonMap);
		userMapper.batchUpdateAliWithdrawOrder(orderParam);//更新支付订单状态
		
		Map<String,Object> batchMap=new HashMap<String, Object>();
		batchMap.put("status", 2);//已做回调处理
		batchMap.put("finishTime", Calendar.getInstance().getTime());
		batchMap.put("notifyId", notify_id);
		batchMap.put("batchOrderId", batchOrder.getId());
		userMapper.updateBatchWithdrawOrder(batchMap);//更新批量付款订单状态
		
		//提现成功通知
		new Thread(new Runnable() {
			
			public void run() {
				for(String brokerid:brokerids){
					//推送提现成功消息
					User user= userMapper.getUserById(brokerid);
					jPush.pushWithAlias(jPush.getUserClient(), "提现成功，请到您的支付宝查收", user.getNotifyid());
					//记录消息
					
					Message message = new Message("提现成功，请到您的支付宝查收",brokerid,MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(new Timestamp(System.currentTimeMillis()));
					orderMapper.addMessage(message);
				}
			}
		}).start();
		
	}
	
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public void dealWithFailAliBatchWithdrawResult(
			Map<String, WithdrawOrder> failMap, String batch_no,String notify_id) {
		BatchWithdrawOrder batchOrder=userMapper.queryBatchWithdrawOrderByOrderNo(batch_no);
		Map<String,Object> orderParam=new HashMap<String, Object>();
		Map<String,String> reasonMap=new HashMap<String, String>();
		List<String> orderIds=new ArrayList<String>();
		List<String> orderNos=new ArrayList<String>();
		for (Entry<String, WithdrawOrder> entry : failMap.entrySet()) {
			WithdrawOrder order=entry.getValue();
			if(order!=null){
				orderIds.add(order.getWithdrawid());
				orderNos.add(order.getWithdraw_order_no());
				reasonMap.put(order.getWithdrawid(), order.getNotify_desc());
			}
		}
		
		Map<String,Object> queryMap=new HashMap<String, Object>();
		queryMap.put("orderNos", orderNos);
		List<UserWalletLogBean> logs=userMapper.queryBrokerWalletLogsByOrderNo(queryMap);
		if(logs==null||logs.size()<0){//如果交易记录不存在拒绝处理
			return;
		}
		
		Map<String,Object> updateMap=new HashMap<String, Object>();
		Map<String,Object> insertParam=new HashMap<String, Object>();
		Map<String,BigDecimal[]> addMap=new HashMap<String,BigDecimal[]>();
		final List<String> brokerids=new ArrayList<String>();
		for(UserWalletLogBean log:logs){
			BigDecimal[] money =new BigDecimal[2];
			money[0]=log.getPurchase_amount();
			money[1]=log.getTip_amount();
			if(addMap.containsKey(log.getUser_id())){
				BigDecimal[] oldMoney=addMap.get(log.getUser_id());
				oldMoney[0]=oldMoney[0].add(money[0]);
				oldMoney[1]=oldMoney[1].add(money[1]);
				addMap.put(log.getUser_id(), oldMoney);
			}else{
				addMap.put(log.getUser_id(), money);
				brokerids.add(log.getUser_id());
			}
			
		}
		updateMap.put("addMap", addMap);
		insertParam.put("logs", logs);
		userMapper.batchInsertBrokerWalletLog(insertParam);//生成钱包变化记录
		userMapper.batchUpdateBrokerWallet(updateMap);//将冻结的钱转化为可取的代购金额和小费金额
		
		orderParam.put("status", 3);//表示提现失败
		orderParam.put("finishTime", Calendar.getInstance());
		orderParam.put("batchOrderId", batchOrder.getId());
		orderParam.put("ids", orderIds);
		orderParam.put("reasonMap", reasonMap);
		userMapper.batchUpdateAliWithdrawOrder(orderParam);//更新支付订单状态
		
		Map<String,Object> batchMap=new HashMap<String, Object>();
		batchMap.put("status", 2);//已做回调处理
		batchMap.put("finishTime", Calendar.getInstance().getTime());
		batchMap.put("notifyId", notify_id);
		batchMap.put("batchOrderId", batchOrder.getId());
		userMapper.updateBatchWithdrawOrder(batchMap);//更新批量付款订单状态
		
		//提现成功通知
				new Thread(new Runnable() {
					
					public void run() {
						for(String brokerid:brokerids){
							
							//推送提现成功消息
							User user= userMapper.getUserById(brokerid);
							jPush.pushWithAlias(jPush.getUserClient(), "尊敬的经纪人，您好，您的提现支付宝处理失败，提现金额已经回退到您的钱包，给您带来不便，非常抱歉", user.getNotifyid());
							//记录消息
							
							Message message = new Message("尊敬的经纪人，您好，您的提现支付宝处理失败，提现金额已经回退到您的钱包，给您带来不便，非常抱歉",brokerid,MessageCons.USER_TYPE_USER,MessageCons.MESSAGE_TYPE_ORDER);
							message.setCreatetime(new Timestamp(System.currentTimeMillis()));
							orderMapper.addMessage(message);
						}
					}
				}).start();
	}

	@Override
	public BatchWithdrawOrder queryBatchWithdrawOrderByOrderNo(String batchOrderNo) {
		return userMapper.queryBatchWithdrawOrderByOrderNo(batchOrderNo);
	}

	@Override
	public List<WithdrawOrder> queryAliWithdrawOrderByBatchOrderNo(String batchOrderNo) {
		return userMapper.queryAliWithdrawOrderByBatchOrderNo(batchOrderNo);
	}
}
